<?php
namespace jy_area_fee;
defined('BY_JYA') or exit('error');
/*
	经销佣金
	
*/
class commission extends \plugin{
	/*
		生成佣金
	*/
	function create($order){
		if(!$this->setting['isopen']){
			return false;
		}
		$this->order=$order;
		$isgoods=$this->isgoods($order);
		if(!$isgoods){
			return false;
		}
		$member=$this->get('member',array('mid'=>$order['mid']));
		if($member['is_agent'] && !$member['dian_mid']){
			$from_id=$member['agent_id'];
			$this->add_mygoods($order,$from_id);
			//$this->jian_mygoods($order,$member);
		}
		if($this->setting['self_commission']==1){
			$agent_id=$order['mid'];
		}else{
			$agent_id=$member['agent_id'];
		}
		//自购升级
		if($member['is_agent']){
				$this->update('member',array('myorder_price +='=>$order['price']),array('mid'=>$order['mid']));
				$this->model('member')->update_agent_level($order['mid'],$order['id']);
		}
		$this->commission_order=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$this->order['mid'],
			'ordersn'=>$this->order['ordersn'],
			'order_price'=>$this->order['price'],
			'plugin_name'=>$this->order['plugin_name']?:'',
			'commission_money'=>0,
			'sale_money'=>0,
			'ping_money'=>0,
			'jifen'=>0,
			'sale_id'=>$member['sale_id'],
			'agent_id'=>$member['agent_id'],
			'createtime'=>TIMESTAMP,
		);
		$this->dian_mid=$member['daili_id']?:$member['dian_mid'];
		if(!$this->dian_mid){
			$this->dian_mid=$member['mid'];
		}
		$this->send_feetype=1;
		//生成社区代理
		$this->up_areafee($order,$agent_id);
		//生成虚拟币
		if($member['agent_id']){
			$this->up_xunifee($order,$member['agent_id']);
		}
		//佣金计算方式，是否扣除运费
		if($this->setting['commissiontype']==1){
			$this->commission_order['commission_price']=$this->order['price'];
		}else{
			$this->commission_order['commission_price']=$this->order['price']-$this->order['dispatchprice'];
		}
		if($this->dian_mid==$member['mid']){
			//进货销售提成
			$this->create_commission($member,21,true);
		}
		if($member['agent_id'] && $this->dian_mid!=$member['mid']){
			$agent=$this->get('member',array('mid'=>$member['agent_id']));
			//业务员才有奖励
			if($agent['dian_mid']){
				//$agent['level_id']=$this->getcolumn('member',array('mid'=>$agent['dian_mid']),'level_id');
				//直推奖励
				$this->create_commission($agent,20);
				//销售奖励
				$agent['mid']=$member['sale_id'];
				$this->create_commission($agent,21);
			}
			if($member['level_id']==$agent['level_id']){
				//平级奖励
				//$this->create_commission($agent,22);
			}
		}
		//生成经销订单
		$this->insert('order',$this->commission_order);
		if($order['sendtype']==3){
			$status=pdo_getcolumn('jy_weishop_order',array('id'=>$order['id'],'uniacid'=>$_SESSION['uniacid']),'status');
			if($status==3){
				$this->order_complete($order);
			}
		}
		return true;
	}
	/*
		给指定会员的计算佣金
		统一佣金比例佣金计算比较简单
		但是商品独立佣金设置该当如何计算呢？
		首先遍历订单的所有商品
			逐个商品检查是否存在独立佣金规则，如果存在，则将订单中该商品的金额单独拿出来计算佣金，订单金额剩余部分在统一计算佣金
	*/
	function create_commission($member,$type=20,$ismyjin=false){
		if(!$member['mid']){
			return false;
		}
		if($member && $member['is_agent'] && $member['stop']==0){
			//相应会员存在且是经销商且状态正常
			if(!$member['level_id']){
				//获取默认等级佣金比例
				$level_commissions=$this->plugin_setting('default_level');
				$level_id=0;
			}else{
				$level=$this->get('level',array('id'=>$member['level_id'],'uniacid'=>$_SESSION['uniacid']));
				$level_commissions=json_decode($level['commissions'],true);
				$level_id=$level['id'];
			}
			if($type==20){
				$rate_key='tui_rate';
			}elseif($type==21){
				$rate_key='sale_rate';
			}elseif($type==22){
				$rate_key='ping_rate';
			}else{
				$rate_key='1';
			}
			$commission_per=$level_commissions[$rate_key];
			$money=0;
			$merchmoney=0;
			$order_price=$this->commission_order['commission_price'];
			$remark=array(
				'level_id'=>$level_id,
				'commission_level'=>$commission_level,
				'order_price'=>$order_price,
				'goods_commission'=>array(),
			);
			
			//先检查是否存在商品独立佣金规则，如果存在则对订单相应商品部分金额单独计算佣金
			$total_lastcostprice=0;
			//非按笔计算
			if($this->setting['get_buyordernum']!=1){
				foreach($this->order['goods'] as $goods){
					if(!$goods['fee_desc']){
						model('jy_weishop/order')->setfee_desc($goods['orderid']);
					}
					$total_price=$goods['total_price']?$goods['total_price']:pdo_getcolumn('jy_weishop_order_goods',array('id'=>$goods['id']),'total_price');
					$costprice=pdo_getcolumn('jy_weishop_goods',array('id'=>$goods['goodsid']),'costprice');
					$total_costprice=$goods['total']*$costprice;
					$total_lastcostprice +=$total_costprice;
					if($member['dian_mid']){
						$dian_mid=$member['dian_mid'];
					}
					//经销发放-------------
					$merchgoods=pdo_get('jy_weishop_goods',array('id'=>$goods['goodsid']));
					$merch_commission=json_decode($merchgoods['api_data'],true);
					$merch_commission['id']=$merchgoods['id'];
					//如果商品单独设置佣金，将减少本商品的金额
					$order_price=$order_price-$total_price;
					foreach($merch_commission['commissions'] as $gc){
						if($gc['level_id']==0){
							$demomerch_commission_per=$gc[$rate_key];
						}
						if($gc['level_id']!=$level_id){
							continue;
						}else{
							$merch_commission_per=$gc[$rate_key];
							break;
						}
					}
					$merch_commission_per=$merch_commission_per?:$demomerch_commission_per;		
					if(substr($merch_commission_per,-1)=='%'){
						//利润计算
						if($this->setting['commissionfeetype']==2){
							$total_price -=$total_costprice;
							$total_lastcostprice -=$total_costprice;
						}
						$merch_commission_money=($total_price*substr($merch_commission_per,0,-1))/100;
						$merchmoney +=$merch_commission_money;
					}else{
						$merch_commission_money=$merch_commission_per*$goods['total'];
						$merchmoney +=$merch_commission_money;
					}
					//平台发放-销售奖------------
					if($type==21 && $ismyjin){
						$goods_commission=$this->get('goods',array('goods_id'=>$goods['goodsid']));
						$goods_commission['commissions']=$goods_commission['commissions']?json_decode($goods_commission['commissions'],true):array();
						if($goods_commission['ignore'] || !$goods_commission['id']){
							if($goods_commission['ignore']){
								$order_price=$order_price-$total_price;
							}
							//只要有一个商品，没有独立设置经销，就订单计算佣金
							$this->needorder=true;
							continue;
						}
						foreach($goods_commission['commissions'] as $gc){
							if($gc['level_id']==0){
								$demogoods_commission_per=$gc[$rate_key];
							}
							if($gc['level_id']!=$level_id){
								continue;
							}else{
								$goods_commission_per=$gc[$rate_key];
								break;
							}
						}
						$goods_commission_per=$goods_commission_per?:$demogoods_commission_per;		
						if(substr($goods_commission_per,-1)=='%'){
							//利润计算
							if($this->setting['commissionfeetype']==2){
								$total_price -=$total_costprice;
								$total_lastcostprice -=$total_costprice;
							}
							$goods_commission_money=($total_price*substr($goods_commission_per,0,-1))/100;
							$money+=$goods_commission_money;
						}else{
							$goods_commission_money=$goods_commission_per*$goods['total'];
							$money+=$goods_commission_money;
						}
					}
					$remark['goods_commission'][]=array('ordergoodsid'=>$goods['id'],'goods_id'=>$goods['goodsid'],'total_price'=>$total_price,'total'=>$goods['total'],'commission_per'=>$goods_commission_per,'commission_money'=>$goods_commission_money);
				}
			}
			if($this->needorder && false){
				if($order_price>0){
					//利润计算
					if($this->setting['commissionfeetype']==2){
							$order_price -=$total_lastcostprice;
					}
					if(substr($commission_per,-1)=='%'){
						$order_commission_money=($order_price*substr($commission_per,0,-1))/100;
					}else{
						$order_commission_money=$commission_per;
					}
					$money+=$order_commission_money;
					$remark['order_commission']=array('order_price'=>$order_price,'commission_per'=>$commission_per,'commission_money'=>$order_commission_money);
				}
			}
			$remark['commission_money']=$merchmoney;
			//经销发放
			if($merchmoney>0){
				if($type==20){
					$this->commission_order['commission_money']+=$merchmoney;
				}elseif($type==21){
					$this->commission_order['sale_money']+=$merchmoney;
				}elseif($type==22){
					$this->commission_order['ping_money']+=$merchmoney;
				}else{
					$this->commission_order['commission_money']+=$merchmoney;
				}
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$member['mid'],
					'dian_mid'=>$this->dian_mid,
					'level'=>$commission_level,
					'ordersn'=>$this->order['ordersn'],
					'money'=>$merchmoney,
					'jifen'=>$jifen?:0,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'type'=>$type,
					'send_feetype'=>1,
					'status'=>0,
				);
				$this->insert('commission',$new_commission);
				model('jy_weishop/notice')->notice_fenxiao_feeadd($member['mid'],$new_commission['money']);
			}
			//平台发放
			if($money>0 && $type==21){
				$this->commission_order['sale_money']+=$money;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$this->dian_mid,
					'dian_mid'=>$this->dian_mid,
					'level'=>$commission_level,
					'ordersn'=>$this->order['ordersn'],
					'money'=>$money,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'type'=>$type,
					'send_feetype'=>0,
					'status'=>0,
				);
				$this->insert('commission',$new_commission);
				model('jy_weishop/notice')->notice_fenxiao_feeadd($this->dian_mid,$new_commission['money']);
			}
			//此处判断经销商是否满足升级条件，如果满足则升级经销商等级
			$member_update=array(
				'order_price'=>$member['order_price']+$this->commission_order['order_price'],
				'order_num'=>$member['order_num']+1,
			);
			if($commission_level==1){
				$member_update['order_price_next']=$member['order_price_next']+$this->commission_order['order_price'];
				$member_update['order_num_next']=$member['order_num_next']+1;
			}
			$this->update('member',$member_update,array('mid'=>$member['mid']));
			$this->model('member')->update_agent_level($member['mid']);
		}
		//如果他的上级是我
		$ta_agent_id=$this->getcolumn('member',array('mid'=>$member['agent_id']),'agent_id');
		if($ta_agent_id==$agent_id){
			return false;
		}
		return $member['agent_id'];
	}
	/*
		虚拟币
	*/
	public function up_xunifee($order,$agent_id){
		if(!$agent_id){
			return false;
		}
		if($this->setting['xuni_open']!=1){
			return false;
		}
		$order_price=$order['price'];
		$money=0;
		$member=$this->get('member',array('mid'=>$agent_id));
		foreach($order['goods'] as $goods){
					$total_price=$goods['total_price']?:pdo_getcolumn('jy_weishop_order_goods',array('id'=>$goods['id']),'total_price');
					$goods_commission=$this->get('goods',array('goods_id'=>$goods['goodsid']));
					if($goods_commission['ignore'] || !$goods_commission['id']){
						$goods_commission=array();
						if($goods_commission['ignore']){
							$order_price=$order_price-$total_price;
						}
						//只要有一个商品，没有独立设置经销，就订单计算佣金
						$this->needorder=true;
						continue;
					}
					$goods_commission['commissions']=$goods_commission['commissions']?json_decode($goods_commission['commissions'],true):array();
					foreach($goods_commission['commissions'] as $gc){
						if($gc['level_id']!=$member['level_id']){
							continue;
						}else{
							$goods_commission_per=$gc['xuni_rate'];
							break;
						}
					}
					if(substr($goods_commission_per,-1)=='%'){
						if(count($order['goods'])==1){
							$total_price=$order_price;
						}
						$goods_commission_money=($total_price*substr($goods_commission_per,0,-1))/100;
						$money +=$goods_commission_money;
					}else{
						$goods_commission_money=$goods_commission_per*$goods['total'];
						$money +=$goods_commission_money;
					}
					//如果商品单独设置佣金，将减少本商品的金额
					$order_price=$order_price-$total_price;
		}
		if($member['level_id'] && $this->needorder){
				$level=$this->get('level',array('id'=>$member['level_id'],'uniacid'=>$_SESSION['uniacid']));
				$level['commissions']=json_decode($level['commissions'],true);
				if(!$level['commissions']['xuni_rate']){
				}else{
					if(substr($level['commissions']['xuni_rate'],-1)=='%'){
						$money +=($order['price']*substr($level['commissions']['xuni_rate'],0,-1))/100;
					}else{
						$money +=$level['commissions']['xuni_rate'];
					}
				}
		}
		$this->commission_order['xuni_money']=$money;
		if($money>0){
				$new_commission=array(
							'uniacid'=>$_SESSION['uniacid'],
							'mid'=>$agent_id,
							'level'=>18,
							'ordersn'=>$order['ordersn'],
							'money'=>$money,
							'createtime'=>TIMESTAMP,
							'status'=>0,
				);
				$this->insert('commission',$new_commission);
		}
	}
	/*
		订单完成时，把佣金状态由初始的订单待完成升级为待结算
	*/
	public function order_complete($order){
		$this->update('commission',array('status'=>1,'complete_time'=>TIMESTAMP),array('ordersn'=>$order['ordersn']));
		$list=$this->getall('commission',array('ordersn'=>$order['ordersn']));
		foreach($list as $info){
			if($info['jifen']>0){
				model('core/member')->add_credit1($info['mid'],$info['jifen'],'佣金兑积分','jy_area_fee');
			}
		}
		//发放补偿金
		$this->send_bufee($order);
	}
	protected function send_bufee($order){
		foreach($order['goods'] as $goods){
			$member=$this->get('member',array('mid'=>$order['mid']));
			$sale_id=$member['sale_id']?:$member['agent_id'];
			if($this->setting['bufee_type']){
				$agent=$this->get('member',array('mid'=>$sale_id));
				if($agent['dian_mid']){
					$mygoods=pdo_get('jy_weishop_goods',array('id'=>$goods['goodsid']));
					$mygoods['api_data']=json_decode($mygoods['api_data'],true);
					$mygoods['bufee']=$mygoods['api_data']['bufee'];
					$dian_credit2=pdo_getcolumn('core_members',array('id'=>intval($agent['dian_mid'])),'credit'.$this->setting['bufee_type']);
					$params=array(
							'mid'=>$order['mid'],
							'dian_mid'=>$agent['dian_mid'],
							'msg'=>'商品补偿金',
							'fee'=>$mygoods['bufee'],
							'status'=>1,
					);
					if($mygoods['bufee']>0 && $dian_credit2>=$mygoods['bufee']){
						model('core/member')->member_credit($order['mid'],'credit'.$this->setting['bufee_type'],$mygoods['bufee'],true,'jy_area_fee','商品补偿金');
						model('core/member')->member_credit($agent['dian_mid'],'credit'.$this->setting['bufee_type'],$mygoods['bufee'],false,'jy_area_fee','商品补偿金');					
						$this->model('model')->set_log($params,0);
					}else{
						if($mygoods['bufee']>0){
							$params['status']=0;
							$this->model('model')->set_log($params,0);
						}
					}
				}
			}else{
				$mygoods=$this->get('goods',array('goods_id'=>$goods['goodsid']));
				if($mygoods['bufee']>0 && $this->setting['bufee_type']){
					model('core/member')->member_credit($order['mid'],'credit'.$this->setting['bufee_type'],$mygoods['bufee'],true,'jy_area_fee','商品补偿金');
					$params=array(
							'mid'=>$order['mid'],
							'msg'=>'商品补偿金',
							'fee'=>$mygoods['bufee'],
							'status'=>1,
					);
					$this->model('model')->set_log($params,0);
				}
			}
		}
		return true;
	}
	protected function add_mygoods($order,$from_id=0){
		foreach($order['goods'] as $goods){
			//$isgoods=$this->get('goods',array('goods_id'=>$goods['goodsid']));
			//if(!$isgoods['id']){
			//	continue;
			//}
			//商户添加商品
			model('jy_merch/model')->checkadd_goods($goods);
		}
		return true;
	}
	protected function jian_mygoods($order,$member=array()){
		foreach($order['goods'] as $goods){
			$isgoods=$this->get('goods',array('goods_id'=>$goods['goodsid']));
			if(!$isgoods['id']){
				continue;
			}
		}
		return true;
	}
	/*
		确实是否本插件商品
	*/
	protected function isgoods($order){
		if($order['merchid']){
			return true;
		}
		foreach($order['goods'] as $goods){
			$goods_commission=$this->get('goods',array('goods_id'=>$goods['goodsid']));
			if($goods_commission['ignore'] || (!$goods_commission['id'] && !$goods['merchid'])){
				continue;
			}else{
				$isgoods=true;
			}
		}
		return $isgoods;
	}
	/*
		创建结算单
	*/
	public function create_balance($mid,$post=array()){
		if(!$mid){
			exi('请先选择要结算的会员！','error');
		}
		if($post['pay_type']=='alipay'){
			if(!$post['realname']){
				exi('请先填写真实姓名！','error');
			}
			if(!$post['alipay']){
				exi('请先填写支付宝帐号！','error');
			}
			if(!$post['alipay1']){
				exi('请确认帐号','error');
			}
			if($post['alipay1']!=$post['alipay']){
				exi('确认帐号与支付宝帐号不匹配！','error');
			}
			$typetitle='支付宝';
		}
		if($post['pay_type']=='union'){
			if(!$post['realname']){
				exi('请输入姓名','error');
			}
			if(!$post['bankname']){
				exi('请输入所属银行','error');
			}
			if(!$post['bankcard']){
				exi('请银行卡号','error');
			}
			if(!$post['bankcard1']){
				exi('请确认卡号','error');
			}
			if($post['bankcard']!=$post['bankcard1']){
				exi('确认卡号与银行卡号不匹配！','error');
			}
			$typetitle='银行卡';
		}
		//获取可结算佣金
		$params=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'status'=>1);
		if($this->setting['balance_day']){
			//结算天数
			$time=TIMESTAMP-intval($this->setting['balance_day'])*86400;
			$params['complete_time <']=$time;
		}
		$money=$this->pdo_getsum('commission',$params,'money');
		$commission_num=$this->count('commission',$params,'id');
		$sysparams=$params;
		if(!$commission_num){
			exi('没有可结算的佣金！','error');
		}
		$params['send_feetype']=1;
		$params['dian_mid >']=0;
		$dianparams=$params;
		$dian_money=$this->pdo_getsum('commission',$params,'money');
		//结算最低佣金检测
		if($money<$this->setting['balance_money']){
			exi('可结算佣金太少，无法结算！','error');
		}
		$sys_money=$money-$dian_money;
		$new_balance=array(
				'uniacid'=>$_SESSION['uniacid'],
				'mid'=>$mid,
				'balancesn'=>get_ordersn($this->tablename('commission'),'balancesn','AC'),
				'commission_num'=>$commission_num,
				'money'=>$sys_money,
				'pay_type'=>$post['pay_type'],
				'realname'=>$post['realname'],
				'alipay'=>$post['alipay'],
				'bankname'=>$post['bankname'],
				'bankcard'=>$post['bankcard'],
				'createtime'=>TIMESTAMP,
				'status'=>0,
		);
		if($sys_money>0){
			//结算手续费
			if($this->setting['balance_per']){
				$new_balance['balance_pay']=intval($new_balance['money']*$this->setting['balance_per'])/100;
			}else{
				$new_balance['balance_pay']=0;
			}
			$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
			$new_balance['send_feetype']=0;
			$this->insert('balance',$new_balance);
			$balance_id=pdo_insertid();
			$update=array(
				'status'=>2,
				'balancesn'=>$new_balance['balancesn'],
			);
			$sysparams['send_feetype']=0;
			$this->update('commission',$update,$sysparams);
		}
		//经销商审核
		if($dian_money>0){
			$dian_commission=$this->getall('commission',$dianparams,array('dian_mid','money'));
			$updian=array();
			foreach($dian_commission as $dv){
				$updian[$dv['dian_mid']]=$updian[$dv['dian_mid']]?:array('money'=>0,'num'=>0);
				$updian[$dv['dian_mid']]['money'] +=$dv['money'];
				$updian[$dv['dian_mid']]['num'] +=1;
			}
			foreach($updian as $k=>$uv){
				$new_balance['balancesn']=get_ordersn($this->tablename('commission'),'balancesn','AC');
				$new_balance['commission_num']=$uv['num'];
				$new_balance['dian_mid']=$k;
				$new_balance['money']=$uv['money'];
				if($this->setting['balance_per']){
					$new_balance['balance_pay']=intval($new_balance['money']*$this->setting['balance_per'])/100;
				}else{
					$new_balance['balance_pay']=0;
				}
				$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
				$new_balance['send_feetype']=1;
				$this->insert('balance',$new_balance);
				$update=array(
					'status'=>2,
					'balancesn'=>$new_balance['balancesn'],
				);
				$sysparams['dian_mid']=$new_balance['dian_mid'];
				$sysparams['send_feetype']=1;
				$this->update('commission',$update,$sysparams);
			}
		}
		if($post['pay_type']=='credit'){
			$typetitle='余额';
		}
		if($post['pay_type']=='wechat'){
			$typetitle='微信';
		}
		$this->model('notice')->notice_fenxiao_tixian($mid,$money,$typetitle);
		return $balance_id;
	}
	public function create_feebalance($mid,$post=array()){
		if(!$mid){
			exi('请先选择要结算的会员！','error');
		}
		$feetype=$post['feetype'];
		if($post['pay_type']=='alipay'){
			if(!$post['realname']){
				exi('请先填写真实姓名！','error');
			}
			if(!$post['alipay']){
				exi('请先填写支付宝帐号！','error');
			}
			if(!$post['alipay1']){
				exi('请确认帐号','error');
			}
			if($post['alipay1']!=$post['alipay']){
				exi('确认帐号与支付宝帐号不匹配！','error');
			}
			$typetitle='支付宝';
		}
		if($post['pay_type']=='union'){
			if(!$post['realname']){
				exi('请输入姓名','error');
			}
			if(!$post['bankname']){
				exi('请输入所属银行','error');
			}
			if(!$post['bankcard']){
				exi('请银行卡号','error');
			}
			if(!$post['bankcard1']){
				exi('请确认卡号','error');
			}
			if($post['bankcard']!=$post['bankcard1']){
				exi('确认卡号与银行卡号不匹配！','error');
			}
			$typetitle='银行卡';
		}
		//获取可结算佣金
		$params=array('uniacid'=>$_SESSION['uniacid'],'dian_mid'=>$mid,'status'=>1,'type'=>0,'feetype'=>$feetype);
		$money=$this->pdo_getsum('feelog',$params,'money');
		$commission_num=$this->count('feelog',$params,'id');
		if(!$commission_num){
			exi('没有可结算的金额！','error');
		}
		//结算最低佣金检测
		if($money<1){
			exi('可结算金额太少，无法结算！','error');
		}
		$feetitle=$this->credit_type[$feetype];
		$new_balance=array(
				'uniacid'=>$_SESSION['uniacid'],
				'mid'=>$mid,
				'balancesn'=>get_ordersn($this->tablename('commission'),'balancesn','AC'),
				'commission_num'=>$commission_num,
				'money'=>$money,
				'pay_type'=>$post['pay_type'],
				'realname'=>$post['realname'],
				'alipay'=>$post['alipay'],
				'bankname'=>$post['bankname'],
				'bankcard'=>$post['bankcard'],
				'createtime'=>TIMESTAMP,
				'status'=>0,
				'remark'=>'结算下级'.$feetitle.'充值',
		);
		//结算手续费
		if($this->setting['balance_per']){
				$new_balance['balance_pay']=intval($new_balance['money']*$this->setting['balance_per'])/100;
		}else{
				$new_balance['balance_pay']=0;
		}
		$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
		$new_balance['send_feetype']=0;
		$this->insert('balance',$new_balance);
		$balance_id=pdo_insertid();
		$update=array(
				'status'=>2,
				'balancesn'=>$new_balance['balancesn'],
		);
		$this->update('feelog',$update,$params);
		if($post['pay_type']=='credit'){
			$typetitle='余额';
		}
		if($post['pay_type']=='wechat'){
			$typetitle='微信';
		}
		$this->model('notice')->notice_fenxiao_tixian($mid,$money,$typetitle);
		return $balance_id;
	}
	/*
		审核结算单
	*/
	public function check_balance($balance_id,$status,$remark=''){
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
			'remark'=>$remark,
		);
		$this->update('balance',$update,array('id'=>$balance_id));
	}
	/*
		打款结算单
	*/
	public function pay_balance($balance_id,$pay_type='',$wxgid='',$pay_trade_no=''){
		$balance=$this->get('balance',array('id'=>$balance_id,'uniacid'=>$_SESSION['uniacid']));
		if(!$balance || $balance['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			//exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		if($balance['dian_mid'] && ($pay_type=='credit' || $pay_type=='wechat')){
			$dian_credit2=pdo_getcolumn('core_members',array('id'=>$balance['dian_mid']),'credit2');
			if($dian_credit2 < $balance['final_money']){
				$params=array(
							'mid'=>$balance['mid'],
							'dian_mid'=>$balance['dian_mid'],
							'msg'=>'佣金打款',
							'fee'=>$balance['final_money'],
				);
				$params['status']=0;
				$this->model('model')->set_log($params,1);
				exi('您的奖金池不足，打款失败！','error');
			}
			model('core/member')->cut_credit2($balance['dian_mid'],$balance['final_money'],'佣金打款','jy_area_fee');
		}
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($balance['mid'],$balance['final_money'],$balance['balancesn'],$wxgid);
		$update=array(
			'status'=>3,
			'pay_trade_no'=>$trade_no=='pay_trade_no'?$pay_trade_no:$trade_no,
			'pay_time'=>TIMESTAMP,
		);
		if($pay_type){
			$update['pay_type']=$pay_type;
		}
		$this->update('balance',$update,array('id'=>$balance['id']));
		$this->model('notice')->notice_fenxiao_dakuan($balance['mid'],$balance['final_money']);
		return true;
	}
	/*
		打款到余额
	*/
	protected function pay_balance_by_credit($mid,$money,$balancesn){
		return cfc('core')->member_credit($mid,'credit2',$money,true,$this->plugin_name,$remark='经销佣金打款');
	}
	/*
		打款到微信零钱
	*/
	protected function pay_balance_by_wechat($mid,$money,$balancesn,$wxgid=''){
		if($wxgid){
			$wxapp=pdo_get('core_account_wxapp',array('id'=>$wxgid,'uniacid'=>$_SESSION['uniacid']),array('appid','mchid','paykey'));
		}
		$params=array(
			'appid'=>$wxapp['appid']?:'',
			'mch_id'=>$wxapp['mchid']?:'',
			'openid'=>$mid,
			'mch_billno'=>$balancesn,
			'money'=>$money,
			'wxgid'=>$wxgid,
			'remark'=>'代理商佣金发放',
		);
		$res=cfc('wechat_pay')->mch_pay($params);
		return $res['payment_no'];
	}
	/*
		打款到支付宝
	*/
	protected function pay_balance_by_alipay($mid,$money,$balancesn){
		return 'pay_trade_no';
		exi('暂不支持打款到支付宝！','error');
	}
	/*
		打款到银行账户
	*/
	protected function pay_balance_by_union($mid,$money,$balancesn){
		return 'pay_trade_no';
		exi('暂不支持打款到银行账户！','error');
	}

	public function commission_remark($remark){
		if(!$remark){
			return '';
		}
		$remark=json_decode($remark,true);
		$goods_str='';
		if($remark['goods_commission']){
			foreach($remark['goods_commission'] as $goods){
				$goods['title']=pdo_getcolumn('jy_weishop_goods',array('id'=>$goods['goods_id']),'title');
				$goods_str.="商品ID【{$goods['goods_id']}】，商品名称【{$goods['title']}】，商品数量【{$goods['total']}】，商品总价【{$goods['total_price']}】，佣金规则【{$goods['commission_per']}】，经销佣金【{$goods['commission_money']}】\n";
			}
		}else{
			$goods_str='未启用';
		}
		$remark['level_title']=pdo_getcolumn('jy_area_fee_level',array('uniacid'=>$_SESSION['uniacid'],'level'=>$remark['commission_level']),'title');
		$remark['level_title']=$remark['level_title']?:'默认等级';
		$remark_str=<<<TPL
经销商等级ID【{$remark['level_id']}】，等级名称【{$remark['level_title']}】，佣金等级【{$remark['commission_level']}】，订单总价【{$remark['order_price']}】
商品独立佣金：
{$goods_str}
订单佣金：
除去设置独立佣金的商品外订单金额【{$remark['order_commission']['order_price']}】，佣金规则【{$remark['order_commission']['commission_per']}%】，经销佣金【{$remark['order_commission']['commission_money']}】
佣金总计：【{$remark['commission_money']}】
TPL;
		return $remark_str;
	}
	/*
		获取单独商品佣金
	*/
	protected function get_goodsfee($goodsid,$orderid,$ordergoodsid=''){
		$ordersn=pdo_getcolumn('jy_weishop_order',array('id'=>$orderid,'uniacid'=>$_SESSION['uniacid']),'ordersn');
		$commissionremark=$this->pdo_getcolumn('commission',array('ordersn'=>$ordersn,'uniacid'=>$_SESSION['uniacid']),'remark');
		//print_r($ordersn.'~~'.$commissionremark);exit;
		$commissionremark=json_decode($commissionremark,true);
		
		$goodsfee=0;
		if($commissionremark['goods_commission']){
			foreach($commissionremark['goods_commission'] as $gv){
				if($ordergoodsid){
					if($ordergoodsid==$gv['ordergoodsid']){
						$goodsfee +=$gv['commission_money'];
					}
				}else{
					if($goodsid==$gv['goods_id']){
						$goodsfee +=$gv['commission_money'];
					}
				}
			}
		}
		if($commissionremark['order_commission'] && $goodsfee==0){
			$allorderfee=pdo_getsum('jy_weishop_order_goods',array('orderid'=>$orderid,'goodsid'=>$goodsid),'total_price');
			//exi($allorderfee.'~'.$commissionremark['order_commission']['order_price'].'~'.$commissionremark['order_commission']['commission_money'],'error');
			$goodsfee=($allorderfee/$commissionremark['order_commission']['order_price'])*$commissionremark['order_commission']['commission_money'];
		}
		return $goodsfee;
	}
}